package com.supermap.filetransfer.network.utils;

import android.util.Log;

import com.supermap.filetransfer.network.listeners.IHttpRequestListener;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.http2.Header;

/**
 * @author Huang.MinJie
 * @desc 网络请求工具类
 * @date 2022-06-19 19:30
 */
public class HttpUtils {
    private final static String TAG = "网络请求: ";

    /**
     * @param url      下载连接
     * @param dirFile  下载的文件储存目录
     * @param fileName 下载文件名称，后面记得拼接后缀，否则手机没法识别文件类型
     * @param listener 下载监听
     * @param headers   请求头
     */
    public static void download(String url, String dirFile, String fileName, IHttpRequestListener listener, Map<String,String> headers) {
        if (isNull(url)) {
            Log.e(TAG, "下载路径为空路径");
            return;
        }
        if (listener == null) {
            Log.e(TAG, "下载监听不能为空");
            return;
        }
        Request request;
        if (headers!=null&&headers.size()>0){
            request = new Request.Builder()
                    .url(url).headers(Headers.of(headers))
                    .build();
        }else{
            request = new Request.Builder()
                    .url(url)
                    .build();
        }
        OkHttpClient client = new OkHttpClient();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    if (listener!=null){
                        listener.onFailure(call, e);
                    }
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (listener!=null){
                        listener.onResponse(call, response);
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            listener.onError(e);
        }

    }


    private static boolean isNotEntity(String contents) {
        return contents != null && !"".equals(contents.trim());
    }

    private static boolean isNull(String content) {
        return content == null || content.trim().length() < 1;
    }
}
